package com.easychat.controller;

import io.github.lnyocly.ai4j.listener.SseListener;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletion;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatMessage;
import io.github.lnyocly.ai4j.service.IChatService;
import io.github.lnyocly.ai4j.service.PlatformType;
import io.github.lnyocly.ai4j.service.factor.AiService;
import okhttp3.sse.EventSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
@CrossOrigin(origins = {}, allowedHeaders = "*", methods = {})
public class ChatAssistController {
    // 注入Ai服务
    @Autowired
    private AiService aiService;

    @GetMapping("/chatStream")
    public SseEmitter getChatMessageStream(@RequestParam String question) throws Exception {
        System.out.println("......................方法成功请求...........................");
        //服务器发送事件（SSE）
        SseEmitter emitter = new SseEmitter();

        //获取ZhiPu AI的聊天服务
        IChatService chatService = aiService.getChatService(PlatformType.ZHIPU);//Zhipu(智谱)平台

        // 创建请求参数
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model("glm-4-flash")//语言模型
                .message(io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatMessage.withUser(question))
                .build();

        SseListener sseListener = new SseListener() {
            @Override
            protected void send() {
                try {
                    emitter.send(this.getCurrStr());
                    System.out.println(this.getCurrStr());  // 打印当前发送的内容
                    if ("[DONE]".equals(this.getCurrStr())) {
                        emitter.complete();
                    }
                } catch (IOException e) {
                    emitter.completeWithError(e);
                }
            }
        };

        emitter.onCompletion(() -> {
            System.out.println("完成");
            sseListener.getEventSource().cancel();
        });

        // 发送流式数据
        sseListener.getCountDownLatch().countDown(); // 取消同步阻塞
        chatService.chatCompletionStream(chatCompletion, sseListener);

        return emitter;
    }

}
